import { MapView } from 'react-native-amap3d'
import React, { Fragment } from 'react'
import {
  View,
  StyleSheet,
  TextInput,
  Text,
  
  ScrollView,
  Platform
} from 'react-native'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import CustomImage from 'src/components/image/CustomImage'
import { getLocationsText, getLocationsAround } from 'src/utils/RequestAPI'
import { getCurrentPosition } from 'src/store/actions/landmark'
import { ONE_PIXEL } from '@/utils/ScreenUtil'
import styles from './css/index'
import debounce from 'lodash/debounce'
/* redux */
//
import { connect } from 'react-redux'
@connect(({ landmark }) => ({
  landmark
}))
class CompanyMapView extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      isShow: false,
      isChonge: false,
      mapViewList: [],
      onClickitem: {}
    }
  }

  onClick = ({ item }) => {
    this.setState({
      onClickitem: item,
      isShow: false,
      isChonge: false
    })
  }

  onFocus = () => {
    this.setState({
      isShow: true,
      isChonge: true
    })
  }

  positionCurrentClick = () => {
    getCurrentPosition().then(({ lat: latitude, lng: longitude }) => {
      this.setState({
        onClickitem: {
          ...this.state.onClickitem,
          location: longitude + ',' + latitude
        }
      })
    })
  }

  onSubmitEditing = ({ nativeEvent: { text, eventCount, target } }) => {
    this.onChange(text)
  }

  onStatusChangeComplete = ({
    nativeEvent: {
      longitude,
      latitude,
      longitudeDelta,
      latitudeDelta,
      rotation,
      zoomLevel,
      tilt
    }
  }) => {
    this.debouncegetLocationsAround(longitude, latitude)
  }

  debouncegetLocationsAround = debounce((longitude, latitude) => {
    if (!this.state.isChonge) {
      getLocationsAround({ params: { location: longitude + ',' + latitude } }).then(data => {
        let item = data.pois[0]
        const lng = longitude
        const lat = latitude
        const operation = item => {
          return item < 0 ? item * -1 : item
        }
        data.pois.map(ite => {
          const location = ite.location.split(',')
          if (
            operation(lng - location[0]) <=
            operation(lng - item.location.split(',')[0]) &&
            operation(lat - location[1]) <=
            operation(lat - item.location.split(',')[1])
          ) {
            item = ite
          }
        })
        this.setState({
          onClickitem: item,
          mapViewList: data.pois
        })
      })
    }
  }, 5000, { maxWait: 10 })

  onStatusChange = ({
    nativeEvent: {
      longitude,
      latitude
    }
  }) => {
    this.debounceTextChange(longitude, latitude)
  }

  onBlur = () => {
    this.setState({
      isChonge: false
    })
  }

  debounceTextChange = debounce((longitude, latitude) => {
    this.setState({
      onClickitem: {
        ...this.state.onClickitem,
        location: longitude + ',' + latitude
      }
    })
  }, 500, { maxWait: 10 })

  childRender () {
    const { isShow, mapViewList, onClickitem } = this.state
    return (
      <View style={styles.container}>
        <View>
          <TextInput
            onBlur={this.onBlur}
            onSubmitEditing={this.onSubmitEditing}
            onFocus={this.onFocus}
            keyboardType={Platform.OS == 'ios' ? 'web-search' : 'default'}
            onChangeText={this.onChange}
            style={styles.TextInput}
            placeholder="请输入办公大楼，例：冠捷大厦"
          />
          <CustomImage
            onPress={this.onChange}
            style={styles.CustomImage}
            source={require('@/imgC/company/company_search.png')}
          />
          {!!isShow && mapViewList.length > 0 && (
            <ScrollView style={styles.search}>
              {(mapViewList || []).map((item, index) => {
                return (
                  <CustomButton
                    onPress={this.onClick}
                    params={{ item }}
                    style={[styles.item]}
                    key={index}
                  >
                    <View style={styles.right}>
                      <Text
                        style={[
                          styles.rightTitle]}
                      >
                        {item.name}
                      </Text>
                      <Text style={styles.rightText}>
                        {(item.pname == item.cityname ? '' : item.pname) +
                          item.cityname +
                          item.adname +
                          item.address}
                      </Text>
                    </View>
                  </CustomButton>
                )
              })}
            </ScrollView>
          )}
        </View>
        <MapView
          ref={ref => {
            this._mapView = ref
          }}
          style={styles.mapViews}
          locationEnabled
          coordinate={{
            latitude: ((onClickitem || {}).location || '').split(',')[1] * 1 || 31.247674153645832,
            longitude: ((onClickitem || {}).location || '').split(',')[0] * 1 || 121.46031711154514
          }}
          zoomLevel={14}
          showsCompass={false}
          rotation={0}
          onStatusChange={this.onStatusChange}
          onStatusChangeComplete={this.onStatusChangeComplete}
        >
          <CustomButton
            style={[styles.mapbtn, styles.mapbtn2]}
            onPress={this.positionCurrentClick}
          >
            <CustomImage source={require('@/imgC/company/location.png')} />
          </CustomButton>
          {(onClickitem || {}).location && (
            <MapView.Marker
              icon={this.icon}
              title={onClickitem.address}
              description={
                (onClickitem.pname == onClickitem.cityname
                  ? ''
                  : onClickitem.pname) +
                onClickitem.cityname +
                onClickitem.adname
              }
              coordinate={{
                latitude: onClickitem.location.split(',')[1] * 1 || 31.247674153645832,
                longitude: onClickitem.location.split(',')[0] * 1 || 121.46031711154514
              }}
            />
          )}
        </MapView>
        {!isShow && mapViewList.length > 0 && (
          <ScrollView>
            {(mapViewList || []).map((item, index) => {
              return (
                <CustomButton
                  onPress={this.onClick}
                  params={{ item }}
                  style={[styles.item]}
                  key={index}
                >
                  <View
                    style={[
                      styles.leftIcon,
                      onClickitem.id == item.id && {
                        backgroundColor: '#63D3A5'
                      }
                    ]}
                  />
                  <View style={styles.right}>
                    <Text
                      style={[
                        styles.rightTitle,
                        onClickitem.id == item.id && { color: '#63D3A5' }
                      ]}
                    >
                      {item.name}
                    </Text>
                    <Text style={styles.rightText}>
                      {(item.pname == item.cityname ? '' : item.pname) +
                        item.cityname +
                        item.adname +
                        item.address}
                    </Text>
                  </View>
                </CustomButton>
              )
            })}
          </ScrollView>
        )}
      </View>
    )
  }

  onChange = e => {
    getLocationsText({ params: { keywords: e, city: this.props.landmark.cityName } }).then(data => {
      this.setState({
        mapViewList: data.pois,
        isShow: true
      })
    })
  }

  icon = () => {
    return (
      <CustomImage
        style={styles.icon}
        source={require('src/imgC/company/map_view_icon.png')}
      />
    )
  }

  renderNavigationBarChild = () => {
    return (
      <CustomButton style={[styles.naviBtnBG]} onPress={this.prewClick}>
        <Text>保存</Text>
      </CustomButton>
    )
  }

  getLocationsAround = (longitude, latitude) => {
    getLocationsAround({ params: { location: longitude + ',' + latitude } }).then(data => {
      let item = data.pois[0]
      const lng = this.props.navigation.state.params.location.split(',')[0]
      const lat = this.props.navigation.state.params.location.split(',')[1]
      const operation = item => {
        return item < 0 ? item * -1 : item
      }
      data.pois.map(ite => {
        const location = ite.location.split(',')
        if (
          operation(lng - location[0]) <=
          operation(lng - item.location.split(',')[0]) &&
          operation(lat - location[1]) <=
          operation(lat - item.location.split(',')[1])
        ) {
          item = ite
        }
      })
      this.setState({
        onClickitem: item,
        mapViewList: data.pois
      })
    })
  }

  componentDidMount () {
    const location =
      (this.props.navigation.state.params &&
        (this.props.navigation.state.params || {}).location) ||
      '121.45573,31.249563'
    if ((!this.props.navigation.state.params || {}).location) {
      getCurrentPosition().then(({ lat: latitude, lng: longitude }) => {
        this.getLocationsAround(longitude, latitude)
      }).catch(() => {
        this.getLocationsAround(121.45573, 31.249563)
      })
    } else {
      this.getLocationsAround(location.split(',')[0], location.split(',')[1])
    }
  }

  prewClick = () => {
    const {
      navigation: {
        state: {
          params: { getData }
        }
      }
    } = this.props
    getData(this.state.onClickitem)
    this.jumpFn()
  }

  jumpFn = () => {
    this.props.navigation.navigate('BusinessAddress')
  }
}

export default CompanyMapView
